package net.zjitc.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.zjitc.common.ResponseResult;
import net.zjitc.security.model.AuthenticationToken;
import net.zjitc.security.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ResponseResult<Object> result = new ResponseResult<>();
        //设置响应头
        response.setContentType("application/json;charset=utf-8");
        //从上下文中取认证信息
        UserDetails userDetails =(UserDetails) authentication.getPrincipal();
        AuthenticationToken token = new AuthenticationToken();


        //生成token的值
        String strToken = jwtTokenUtil.generateToken(userDetails);
        token.setToken(strToken);
        result.setSuccess("登录成功",token);
        //认证信息存到redis........

        //restult转json
        response.getWriter().write(new ObjectMapper().writeValueAsString(result));
    }
}
